﻿using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using System.IO;
using System.Collections.Generic;
using System;

public class ChangePanel : MonoBehaviour
{
    public static  ChangePanel changePanel;

    [Header("UI References")]
    public RectTransform backgroundPanel; // 背景面板
    public Image backgroundImage; // 背景图片组件（用于透明度变化）
    public RectTransform buttonsContainer; // 按钮容器
    public GameObject dotButton1;
    public GameObject dotButton2;
    public GameObject dotButton3;
    public RectTransform purpleButton; // 紫色按钮
    /// <summary>
    /// 方块切换背景板
    /// </summary>
    private RectTransform bottom,Buttons; 


    [Header("Animation Settings")]
    public float collapseDuration = 0.6f;
    public Ease collapseEase = Ease.InOutBack;
    [Header("紫色按钮缩放参数")]
    [Range(0f, 1f)] public float finalScale = 0f; // 最终缩放比例
    [Range(0f, 1f)] public float finalAlpha = 0f; // 最终透明度

    private bool isExpanded = true;
    private Vector3 originalScale;
    private Color originalColor;
    /// <summary>
    /// 紫色按钮初始大小,切换方块按钮位置
    /// </summary>
    private Vector3 originalAnchoredPos, bottomPos;
    /// <summary>
    /// 返回菜单按钮
    /// </summary>
    private Button backBtn;
    /// <summary>
    /// 菜单栏
    /// </summary>
    private Transform HallPanel;
    /// <summary>
    /// 切换按钮
    /// </summary>
    private itemData_switch itemData_Switch;
    /// <summary>
    /// 切换按钮位置
    /// </summary>
    private Transform Switch_tran;
    /// <summary>
    /// 切换按钮字典
    /// </summary>
    private Dictionary<string,itemData_switch> itemData_Switch_dir=new Dictionary<string, itemData_switch>();
    /// <summary>
    /// 下一关按钮
    /// </summary>
    private  Transform The_next_level_Button;
    /// <summary>
    /// 下一块按钮
    /// </summary>
    private Button NextPiece;
    /// <summary>
    /// 当前钻石编号文本
    /// </summary>
    private Text penidText;
    /// <summary>
    /// 当前钻石编号进度条
    /// </summary>
    private Slider numberSlider;
    /// <summary>
    /// 编号背景颜色
    /// </summary>
    private Image numberImage;
    private void Awake()
    {
        if (changePanel==null)
        {
            changePanel = this;
        }
        backBtn = GameObject.Find("top/backBtn").GetComponent<Button>();
        backBtn.onClick.AddListener(ReturnMenu);
        HallPanel = GameObject.Find("HallPanel").GetComponent<Transform>();
        itemData_Switch= Resources.Load<itemData_switch>("Prefab/itemData_switch");
        Switch_tran= GameObject.Find("bottom/Switch_gemstone/Viewport/Content").GetComponent<Transform>();
        bottom = GameObject.Find("bottom").GetComponent<RectTransform>();
       // Buttons = GameObject.Find("Buttons").GetComponent<RectTransform>();
        The_next_level_Button = GameObject.Find("The_next_level_Button").GetComponent<Transform>();
        The_next_level_Button.gameObject.GetComponent<Button>().onClick.AddListener(LoadNextLevel);
        The_next_level_Button.gameObject.SetActive(false);

        //NextPiece = GameObject.Find("top/RightSwitch").GetComponent<Button>();
        //NextPiece.onClick.AddListener(() => GameInit.instance.NextPiece(true));

        penidText = GameObject.Find("top/Stage/Image/Text").GetComponent<Text>();
        numberSlider = GameObject.Find("top/Stage/Slider").GetComponent<Slider>();
        numberImage = GameObject.Find("top/Stage/Image/color").GetComponent<Image>();
    }

    void Start()
    {
        // 存储原始属性
        originalColor = backgroundImage.color;
        originalAnchoredPos = backgroundPanel.anchoredPosition;
        bottomPos = bottom.localScale;
        originalScale = backgroundPanel.localScale;
        // 绑定按钮事件
        purpleButton.GetComponent<Button>().onClick.AddListener(ToggleButtons);
    }

    /// <summary>
    /// 显示当前笔头id
    /// </summary>
    /// <param name="id"></param>
    public void displayPenId(string id)
    {
        penidText.text = id;
        numberImage.color = colorProcessing(id);
        //if (GameInit.instance.paintedCountDict.ContainsKey(id))
        //{
        //    numberSlider.maxValue = GameInit.instance.MapData.mapArrayDic[id];
        //    numberSlider.value = GameInit.instance.paintedCountDict[id];
        //}
        Progress(id);
    }
    public void Progress(string id)
    {
        if (GameInit.instance.paintedCountDict.ContainsKey(id))
        {
            numberSlider.maxValue = GameInit.instance.MapData.mapArrayDic[id];
            numberSlider.value = GameInit.instance.paintedCountDict[id];
        }
    }


    /// <summary>
    /// 打开下一关按钮
    /// </summary>
    public void Open_The_next_level_Button(bool isOpen)
    {
        The_next_level_Button.gameObject.SetActive(isOpen);
    }

    /// <summary>
    /// 下一关
    /// </summary>
    private void LoadNextLevel()
    {
        //bool load = false;
        //foreach(int key in ReadData.instance.mapDataDic.Keys)
        //{
        //    if (GameInit.instance.MapData.id == key)
        //    {
        //        load = true;
        //        continue;
        //    }

        //    if (load)
        //    {
        //        if (ReadData.instance.UnlockOrNot.ContainsKey(key))
        //        {
        //            if (ReadData.instance.UnlockOrNot[key] == 0)
        //            {
        //                AdManager.Instance.ShowVideo(() => {
        //                    ReadData.instance.SetUnlockOrNot(key);
        //                    //_lock.gameObject.SetActive(false);
        //                    GameInit.instance.SetMap(ReadData.instance.mapDataDic[key]);
        //                });
        //                return;
        //            }
        //        }
        //        GameInit.instance.SetMap(ReadData.instance.mapDataDic[key]);
        //        return;
        //    }
        //}
        //if(!load)
        //{
        //    Debug.Log("最后一关");
        //}


        ReturnMenu();

    }

    /// <summary>
    /// 返回菜单栏
    /// </summary>
    private void ReturnMenu()
    {
        if(!MainCamera.instance.isZoomOut)
        {
            return;
        }

        HallPanel.gameObject.SetActive(true);
        ChangePanel.changePanel.Open_The_next_level_Button(false);
    }

    /// <summary>
    /// 初始化切换界面
    /// </summary>
    public void Init_Switch_gemstone()
    {
        ClearTransform(Switch_tran);

        MapData _MapData=GameInit.instance.MapData;
        itemData_Switch_dir = new Dictionary<string, itemData_switch>();
        if (_MapData==null)
        {
            Debug.Log(_MapData.id + "为空");
            return ;
        }
        foreach(string key in _MapData.mapArrayDic.Keys)
        {
            itemData_switch itemData = Instantiate(itemData_Switch, Switch_tran);
            Color _c = colorProcessing(key);

            itemData.Init(key, _MapData.mapArrayDic[key], _c);
            itemData.GetComponent<Button>().onClick.AddListener(() => ClickToSwitch(key));
            if (!itemData_Switch_dir.ContainsKey(key))
            {
                itemData_Switch_dir.Add(key, itemData);
            }
        }

    }
    /// <summary>
    /// 显示对应方块颜色
    /// </summary>
    /// <param name="_MapData"></param>
    /// <param name="key">id</param>
    /// <returns></returns>
    private static Color colorProcessing(string key)
    {
        Color _c = Color.white;
        if (GameInit.instance.MapData.map_color.ContainsKey(key))
        {
            (string, string, string) str = GameInit.instance.MapData.map_color[key].Item1;
            // 安全解析 RGB 值（处理可能的格式错误）
            if (float.TryParse(str.Item1, out float r) &&
                float.TryParse(str.Item2, out float g) &&
                float.TryParse(str.Item3, out float b))
            {
                // 如果输入是 0-255 的整数，需归一化到 0-1
                if (r > 1f || g > 1f || b > 1f)
                {
                    r /= 255f;
                    g /= 255f;
                    b /= 255f;
                }
                _c = new Color(r, g, b);
            }
        }

        return _c;
    }

    /// <summary>
    /// 刷新切换按钮
    /// </summary>
    public void UpProgress(string _id)
    {
        if(itemData_Switch_dir.ContainsKey(_id))
        {
            itemData_Switch_dir[_id].UpProgress();
        }
    }


    /// <summary>
    /// 点击切换
    /// </summary>
    private void ClickToSwitch(string key)
    {
        PenController.instance.Set_currentTargetNumber(key);
        AudioManager.Instance.Play("切换方块");
    }

    /// <summary>
    /// 清空子物体
    /// </summary>
    /// <param name="transform"></param>
    public void ClearTransform(Transform _transform)
    {
        for (int i = _transform.childCount - 1; i >= 0; i--)
        {
            Destroy(_transform.GetChild(i).gameObject);
        }

    }
    /// <summary>
    /// 缩小UI
    /// </summary>
    public void GameCompleted()
    {
       // NextPiece.transform.gameObject.SetActive(false);
        // 圆形收缩动画序列
        Sequence collapseSeq = DOTween.Sequence();
        // 同时进行缩放和透明度变化
        collapseSeq.Join(bottom.DOScale(finalScale, collapseDuration).SetEase(collapseEase));
           // .Join(Buttons.DOScale(finalScale, collapseDuration).SetEase(collapseEase));

    }


    /// <summary>
    /// 恢复Ui到原来大小
    /// </summary>
    public  void RestoreUI()
    {
        if(bottomPos == bottom.localScale&& originalScale == backgroundPanel.localScale)
        {
            return;
        }
        //NextPiece.transform.gameObject.SetActive(true);
        Sequence expandSeq = DOTween.Sequence();
        expandSeq.Join(bottom.DOScale(bottomPos, collapseDuration).SetEase(collapseEase));
        //Slot_list .Join(Buttons.DOScale(originalScale, collapseDuration).SetEase(collapseEase));
        UpButton();
    }

    /// <summary>
    /// 紫色按钮
    /// </summary>
    void ToggleButtons()
    {
        if (DOTween.IsTweening(backgroundPanel)) return;

        isExpanded = !isExpanded;

        if (!isExpanded)
        {
            // 1. 按钮消失动画
            dotButton1.transform.DOScale(0, collapseDuration / 2).SetEase(collapseEase);
            dotButton2.transform.DOScale(0, collapseDuration / 2).SetEase(collapseEase);
            dotButton3.transform.DOScale(0, collapseDuration / 2).SetEase(collapseEase)
                .OnComplete(() => {
                    dotButton1.SetActive(false);
                    dotButton2.SetActive(false);
                    dotButton3.SetActive(false);
                });

            // 2. 圆形收缩动画序列
            Sequence collapseSeq = DOTween.Sequence();

            // 同时进行缩放和透明度变化
            collapseSeq.Join(backgroundPanel.DOScale(finalScale, collapseDuration).SetEase(collapseEase))
                      .Join(backgroundImage.DOFade(finalAlpha, collapseDuration));

            // 移动到紫色按钮位置（计算相对位置）
            Vector2 targetPos = purpleButton.anchoredPosition - backgroundPanel.anchoredPosition;
            collapseSeq.Append(backgroundPanel.DOAnchorPos(targetPos, collapseDuration).SetEase(Ease.OutQuad));
        }
        else
        {
            UpButton();
        }
    }
    /// <summary>
    /// 打开笔夹切换按钮
    /// </summary>
    private void UpButton()
    {
        // 1. 恢复到原始位置和大小
        Sequence expandSeq = DOTween.Sequence();

        expandSeq.Append(backgroundPanel.DOAnchorPos(originalAnchoredPos, collapseDuration).SetEase(Ease.OutQuad))
                .Join(backgroundPanel.DOScale(originalScale, collapseDuration).SetEase(collapseEase))
                .Join(backgroundImage.DOFade(originalColor.a, collapseDuration));

        // 2. 按钮弹出动画（延迟显示）
        expandSeq.OnComplete(() =>
        {
            dotButton1.SetActive(true);
            dotButton2.SetActive(true);
            dotButton3.SetActive(true);

            dotButton1.transform.localScale = Vector3.zero;
            dotButton2.transform.localScale = Vector3.zero;
            dotButton3.transform.localScale = Vector3.zero;

            dotButton1.transform.DOScale(1, collapseDuration / 2).SetEase(Ease.OutBack);
            dotButton2.transform.DOScale(1, collapseDuration / 2).SetEase(Ease.OutBack);
            dotButton3.transform.DOScale(1, collapseDuration / 2).SetEase(Ease.OutBack);
        });
    }
}
